<?php

$servername = "localhost";  //数据库地址
// 数据库名
$dbname = "bak";
// 数据库用户名
$username = "root";
// 数据库密码
$password = "123456";

//保持此API密钥值与项目页面中提供的ESP32代码兼容。
//如果您更改此值，则ESP32草图需要匹配
$api_key_value = "tPmAT5Ab3j7F9";

$api_key= $sensor = $location = $value1 = $value2 = $value3 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $read_post = file_get_contents('php://input');
    $datas=json_decode($read_post, true);

    $api_key = $datas['api_key'];

    if($api_key == $api_key_value) {
        $sensor = $datas['sensor'];
        $location =$datas['location']; 
        $value1 = $datas['value1'];
        $value2 = $datas['value2'];
        $value3 = $datas['value3'];
        $id     = $datas['id'];
        // 创建数据库连接
        $conn = new mysqli($servername, $username, $password, $dbname);
        // 检查数据库连接状态
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        //插入一个新的数据行
        //$sql = "INSERT INTO SensorData ( id, sensor, location, value1, value2, value3)
        //VALUES ('" . $id . "', '" . $sensor . "', '" . $location . "', '" . $value1 . "', '" . $value2 . "', '" . $value3 . "')";

        //更新表中内容
        $sql = mysqli_query($conn,"UPDATE SensorData SET value1 = '".$value1."',value2 = '".$value2."'
            WHERE sensor='Light'");
        //如果数据修改成功
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        }  
        else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    
        $conn->close();
    }
    else {
        echo "Wrong API Key provided.<br/>";
    }

}
else {
    echo "No data posted with HTTP POST.<br/>";
}


?>